import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-securityproblemmodal',
    templateUrl: './securityProblemModal.component.html',
    styleUrls: ['./dispatchList.component.less']
})
export class SecurityProblemModalComponent implements OnInit {
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() width: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    thisData: any = { 'count': 0, 'id': [] };

    detailObj: any = { 'class': 'packup', 'text': '详情展开' };
    gzxmList = [];
    jcbmNodes = [];
    jcbmList = [];
    jcddAutoData = [];
    jcddTempData = [];
    zrbmNodes = [];
    zrbmList = [];
    wtlbNodes = [];
    wtlbList = [];
    czNodes = [];
    czList = [];
    sblxNodes = [];
    sblxList = [];
    sbmcNodes = [];
    tbzrbmNodes = [];
    xfzrbmNodes = [];
    wtxxInfo = '';
    zrbmInfo = '';
    treeNodeStyle = { 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    isLoading: any = {};
    wtlbCompareFn = (o1: any, o2: any) => (o1 && o2 ? o1.code === o2.code : o1 === o2);
    tbzrbmCompareFn = (o1: any, o2: any) => (o1 && o2 ? o1.ID === o2.ID : o1 === o2);

    constructor(
        private msg: NzMessageService,
        public ls: LocalStorage,
        private datePipe: DatePipe,
        public treeTools: TreeTools,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        if (!this.width) {
            this.width = '500';
        }
        this.getOperaApi('update', () => {
            const loginInfo = JSON.parse(this.ls.get('loginInfo'));
            this.operaData.checkOrgId = loginInfo.VC_ORG$ID;
            this.operaData.chargeOrgId = loginInfo.VC_ORG$ID;
            this.operaData.checkPerson = loginInfo.VC_NAME;
            // this.operaData.checkDate = new Date();

            // 把完成情况反馈字段对应到问题库字段
            this.operaData.checkDate = this.responseData.dtWorkdate;
            this.operaData.sourceId = this.responseData.vcId;
            this.operaData.sourceType = "1";
            // this.responseData.sedate;
            // this.responseData.staName;
            // this.responseData.vcDaypalnid;
            this.operaData.devId = [this.responseData.vcDevid];
            // this.responseData.vcDevname;
            // this.responseData.vcId;
            this.operaData.checkOrgId = this.responseData.vcOrgId;
            this.operaData.stationId = this.responseData.vcStaid;
            // this.responseData.vcYearMonth;
            // this.responseData.waName;
            // this.responseData.wsName;
        });
    }
    getOperaApi(type, callback) {
        setTimeout(() => {
            this.Visible = true;
            const updateApi = [
                this.http.get(environment.project + '/sysTDict/getDictByClass?code=SAFE_PROBLEM_PROJECT'),
                this.http.get(environment.apiBase + '/csmis/getKmnOrgTree.jwt?showAll=1&showSeg=1'),
                this.http.get(environment.project + '/sysTDict/getDictByClass?code=SAFE_PROBLEM_TYPE'),
                this.http.get(environment.apiBase + '/csmis/publicTree/getorgstatree.jwt')
            ];
            forkJoin(updateApi).subscribe((results: any) => {
                if (!results[0].code) {
                    this.gzxmList = results[0].data;
                }
                if (results[1]) {
                    Object.assign(this.jcbmNodes, results[1]);
                    this.childToList(this.jcbmList, results[1]);
                    Object.assign(this.zrbmNodes, results[1]);
                    this.childToList(this.zrbmList, results[1]);
                }
                if (!results[2].code) {
                    this.wtlbNodes = results[2].data;
                }
                if (results[3]) {
                    this.czNodes = this.treeTools.formatTreeNode(results[3]);
                    this.childToList(this.czList, results[3]);
                    this.autoToList(this.jcddTempData, results[3]);
                }
                if (callback) {
                    callback()
                }
            });
        }, 200);
    }
    deadlineChange(e) {
        if (e.getTime() - new Date(this.operaData.checkDate).getTime() < 0) {
            this.msg.error('整改时限不能早于检查时间');
            setTimeout(() => {
                this.operaData.deadline = this.operaData.checkDate;
            }, 500);
        }
    }
    czChange(e, callback?) {
        this.sblxNodes = [];
        this.sblxList = [];
        if (e) {
            const url = environment.apiBase + '/csmis/devTypes/getAllTypesByStaId1.jwt?station=' + e;
            this.http.get(url).subscribe((res: any) => {
                this.sblxNodes = this.treeTools.formatTreeNode(res);
                this.childToList(this.sblxList, this.sblxNodes);
                if (callback) {
                    callback();
                }
            });
        }
    }
    lxChange(e, callback?) {
        this.sbmcNodes = [];
        const url = environment.apiBase + '/csmis/publicTree/getDevByStationType.jwt?staid=' + this.operaData.stationId + '&typeid=' + e;
        this.http.get(url).subscribe((res: any) => {
            if (res.type === "success" && res.response.data) {
                this.sbmcNodes = res.response.data;
                if (callback) {
                    callback();
                }
            }
        });
    }
    gzxmChange(e) {
        this.operaData.gzxm = e;
    }
    // children转list
    childToList(array, list) {
        list.forEach(item => {
            array.push(item);
            if (item.children && item.children.length) {
                this.childToList(array, item.children);
            }
        })
    }
    // children转list
    autoToList(array, list) {
        list.forEach(item => {
            array.push(item.text);
            if (item.children && item.children.length) {
                this.autoToList(array, item.children);
            }
        })
    }
    detail() {
        if (this.detailObj.class === 'packup') {
            this.detailObj.class = 'packout';
            this.detailObj.text = '详情收起';
        } else {
            this.detailObj.class = 'packup';
            this.detailObj.text = '详情展开';
        }
    }
    jcddInput(e) {
        const value = e.target.value;
        switch (value) {
            case '':
            case null:
            case undefined:
                this.jcddAutoData = [];
                break;
            default:
                this.jcddAutoData = this.jcddTempData.filter(option => option.indexOf(value) !== -1);
                break;
        }
    }
    Ok() {
        this.isLoading.Ok = true;
        setTimeout(() => {
            this.isLoading.Ok = false;
        }, 2000);
        const param: any = {};
        // if (!this.operaData.gzxm || !this.operaData.gzxm.length) {
        //     this.msg.error('必填项不能为空', { nzDuration: 1000 });
        //     return;
        // } 
        Object.assign(param, this.operaData);
        if (this.operaType === 'edit') {
            param.id = this.operaData.id;
        }
        if (param.typeId) {
            param.typeName = param.typeId.name;
            param.typeId = param.typeId.code;
        }
        param.checkDate = this.datePipe.transform(param.checkDate, 'yyyy-MM-dd');
        param.deadline = this.datePipe.transform(param.deadline, 'yyyy-MM-dd');
        param.projectName = [];
        // 根据ID取NAME
        for (const item of this.gzxmList) {
            if (param.gzxm) {
                for (const data of param.gzxm) {
                    if (data === item.code) {
                        param.projectName.push(item.name);
                    }
                }
            } else {
                param.gzxm = [];
            }
        }
        param.projectName = param.projectName.join(',');
        param.projectId = param.gzxm.join(',');
        param.devName = [];
        if (param.devId) {
            param.devId = this.operaData.devId.join(',');
            for (const item of this.operaData.devId) {
                for (const data of this.sbmcNodes) {
                    if (data.ID === item) {
                        param.devName.push(data.VC_NAME)
                    }
                }
            }
        }
        if (param.devName) {
            param.devName = param.devName.join(',');
            for (const item of this.jcbmList) {
                if (item.key === param.checkOrgId) {
                    param.checkOrgName = item.title;
                    break;
                }
            }
        }
        for (const item of this.zrbmList) {
            if (item.key === param.chargeOrgId) {
                param.chargeOrgName = item.title;
                break;
            }
        }
        for (const item of this.czList) {
            if (item.id === param.stationId) {
                param.stationName = item.text;
                break;
            }
        }
        for (const item of this.sblxList) {
            if (item.key === param.devTypeCode) {
                param.devTypeName = item.title;
                break;
            }
        }
        delete param.gzxm;
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                if (res.msg) {
                    this.msg.error(res.msg);
                } else {
                    this.msg.error('操作失败');
                }
            }
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}
